package com.sgb.kjwl.view.ui.fragment.demandHall;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentCustomerInquiryBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.DemandHallListEntity;
import com.sgb.kjwl.model.entity.EnquiryTypeEntity;
import com.sgb.kjwl.model.entity.GoodsListTypeEntity;
import com.sgb.kjwl.model.entity.IndustryHomeListEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.utils.ActivityClassHelper;
import com.sgb.kjwl.utils.DisplayUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.link.event.MaterialEvent;
import com.sgb.kjwl.view.ui.adapter.carrierDemand.DemandHallAdapter;
import com.sgb.kjwl.view.widget.DemandHallTypePopWindow;
import com.sgb.kjwl.view.widget.Enquirytypepopwindow;
import com.sgb.kjwl.viewmodel.demand.CustomerInquiryModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CustomerInquiryFragment#newInstance} factory method to
 * create an instance of this fragment.
 * by hq 2021.04.10 首页商品模块的需求大厅--客户询价
 *
 * @author Administrator
 */
public class CustomerInquiryFragment extends AppFragment {

    private FragmentCustomerInquiryBinding binding;

    @Inject
    CustomerInquiryModel customerInquiryModel;
    List<DictEntity3> dictData;
    private DemandHallTypePopWindow demandHallTypePopWindow;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;

    List<EnquiryTypeEntity> enquirylist = new ArrayList<>();
    List<EnquiryTypeEntity> sortlist = new ArrayList<>();
    List<EnquiryTypeEntity> userlist = new ArrayList<>();
    private String enquiryid = "0";
    private final String userid = "";
    private String sortid = "2";
    private boolean isLoadMore = false;
    private int page = 1;
    private final String INIT_VALUE = "100";

    private String statusType = INIT_VALUE;
    private String sortType = INIT_VALUE;

    private Enquirytypepopwindow enquirytypepopwindow;
    private Enquirytypepopwindow sortTypepopwindow;
    private DemandHallAdapter demandHallAdapter;
    private String searchName = "";
    private String tabName = "全部";
    private String shoppingNo, context;

    private boolean isUpDragging = true;

    private AppBarLayout.LayoutParams layoutParams;
    private boolean isAppBarExpended = false;
    private static final String TGA = "NewPickSigningUpListFragment";
    private boolean isParentAppBarCollapsed = false;
    /***
     * type 等于0 商品首页-需求大厅的客户询价
     * type 等于1 企业网站-需求公告-商品需求
     */
    private int type;
    private String companyNo = "";


    private List<IndustryHomeListEntity.IndustryItem> list_Industry = new ArrayList<>();

    private int choice_Industry = 0;


    /***
     * @param
     * @return
     */
    public static CustomerInquiryFragment newInstance(int type) {
        CustomerInquiryFragment fragment = new CustomerInquiryFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static CustomerInquiryFragment newInstance(int type, String companyNo) {
        CustomerInquiryFragment fragment = new CustomerInquiryFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putString("companyNo", companyNo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                init();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        isCreate = true;
    }

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_customer_inquiry, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    private void initView() {
        if (getArguments() != null) {
            type = getArguments().getInt("type", 0);
            if (type == 1) {
                companyNo = getArguments().getString("companyNo", "");
            }
        }
        demandHallTypePopWindow = new DemandHallTypePopWindow(getActivity());
        demandHallTypePopWindow.setOnResultClick((key1, key2, key3) -> Objects.requireNonNull(binding.tabLayout.getTabAt((int) key2)).select());
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setTabLayoutName(tab.getPosition());
                demandHallTypePopWindow.setDefItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        if (type == 1) {
            binding.selectLayout.setVisibility(View.VISIBLE);
            binding.tvStatus.setOnClickListener(this);
            binding.tvStatus.setMacText("状态");
            binding.tvRank.setOnClickListener(this);
            binding.tvRank.setMacText("排序");
        } else {
            binding.selectLayout.setVisibility(View.GONE);
        }
        enquirytypepopwindow = new Enquirytypepopwindow(getActivity());
        enquirytypepopwindow.setBgView(binding.bgPopGrayLayout);
        sortTypepopwindow = new Enquirytypepopwindow(getActivity());
        sortTypepopwindow.setBgView(binding.bgPopGrayLayout);
        enquirytypepopwindow.setOnResultClick((key1, key2, key3) -> {
            if (null != key1) {
                enquiryid = ((EnquiryTypeEntity) key1).getId();
                binding.tvStatus.setMacText(((EnquiryTypeEntity) key1).getName());
                statusType = enquiryid;
            }
            getData();
        });
        enquirytypepopwindow.setOnDisMissClick(() -> binding.tvStatus.contentSelect(true, false));
        sortTypepopwindow.setOnResultClick((key1, key2, key3) -> {
            if (null != key1) {
                sortid = ((EnquiryTypeEntity) key1).getId();
                binding.tvRank.setMacText(((EnquiryTypeEntity) key1).getName());
                sortType = sortid;
            }
            getData();
        });
        sortTypepopwindow.setOnDisMissClick(() -> binding.tvRank.contentSelect(true, false));
        layoutParams = (AppBarLayout.LayoutParams) binding.llContainer.getLayoutParams();
        demandHallAdapter = new DemandHallAdapter(getActivity(), null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.demandList.setLayoutManager(layoutManager);
        binding.demandList.setAdapter(demandHallAdapter);
        binding.demandList.setLoadingMoreEnabled(true);
        binding.demandList.setPullRefreshEnabled(false);
        binding.demandList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page = page + 1;
                customerInquiryModel.getDemandHallList(userid, sortid, enquiryid, tabName, searchName, companyNo, page);
            }
        });

        demandHallAdapter.setOnItemClick(new AdapterOnItemClick<DemandHallListEntity>() {
            @Override
            public void onItemClick(DemandHallListEntity demandhalllistentity, int position) {
                shoppingNo = demandhalllistentity.getEnquiryNo();
                context = demandhalllistentity.getItemName();
                customerInquiryModel.showUrl(demandhalllistentity.getEnquiryNo(), context);
            }
        });
        binding.tabIndustry.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                choice_Industry = tab.getPosition();
                if(choice_Industry==0){
                    binding.linChoicelass.setVisibility(View.GONE);
                    setTabLayoutName(0);
                    demandHallTypePopWindow.setDefItem(0);
                }else {

                    customerInquiryModel.getMenuModel(list_Industry.get(choice_Industry).getId()+"");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


//        binding.appBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
//            @Override
//            public void onStateChanged(AppBarLayout appBarLayout, State state) {
//                isAppBarExpended = state == State.EXPANDED;
//            }
//        });
//
//        binding.appBar.post(() -> {
//            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) binding.appBar.getLayoutParams();
//            AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) layoutParams.getBehavior();
//            if (behavior != null) {
//                behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
//                    @Override
//                    public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
//                        return true;
//                    }
//                });
//            }
//        });
        TempAnimationUtils animationUtils = new TempAnimationUtils();
        binding.demandList.addOnScrollListener(new RecyclerViewScrollListener() {
            @Override
            public void hide() {
                /*animationUtils.startAnim(binding.appBar,
                        DisplayUtil.dip2px(getActivity(), 1), 2);*/
                binding.tabIndustry.animate().translationY(-binding.tabIndustry.getHeight()).setInterpolator(new AccelerateDecelerateInterpolator());
            }

            @Override
            public void show() {
                /*animationUtils.startAnim(binding.appBar,
                        DisplayUtil.dip2px(getActivity(), 1), 1);*/
                binding.tabIndustry.animate().translationY(0).setInterpolator(new AccelerateDecelerateInterpolator());

            }
        });

    }
    /***
     *     获取tab页签名称
     */
    private void setTabLayoutName(int position) {
        if (null != dictData && dictData.size() > 0) {
            tabName = dictData.get(position).getName();
            getData();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.tv_status:
                if (null == enquirylist || enquirylist.size() == 0) {
                    return;
                }
                new Handler().postDelayed(() -> enquirytypepopwindow.showPopwindow(binding.selectLayout, 0, 0), 100);
                enquirytypepopwindow.setData(enquirylist);
                binding.tvStatus.contentSelect(false, true);
                break;
            case R.id.tv_rank:
                if (null == sortlist || sortlist.size() == 0) {
                    return;
                }
                new Handler().postDelayed(() -> sortTypepopwindow.showPopwindow(binding.selectLayout, 0, 0), 100);
                sortTypepopwindow.setData(sortlist);
                binding.tvRank.contentSelect(false, true);
                break;
            default:
                break;
        }
    }

    /**
     * 更新选项颜色
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private void updateChooseTextStatus(String type, int status, TextView textView) {
        if (status == 1) {
            textView.setBackground(getResources().getDrawable(R.drawable.corner_gery_button_20_bg));
            Drawable drawable_n = getResources().getDrawable(R.mipmap.icon_up_red);
            drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
            textView.setCompoundDrawables(null, null, drawable_n, null);
        } else {
            textView.setBackground(getResources().getDrawable(R.drawable.corner_blue_button_20_bg));
            Drawable drawable_n = getResources().getDrawable(R.mipmap.icon_down_red);
            drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
            textView.setCompoundDrawables(null, null, drawable_n, null);
        }
        textView.setTextColor(getResources().getColor(R.color.color_main));
    }

    private void init() {
        if (type == 0) {
//            customerInquiryModel.getDemandHallList();
            customerInquiryModel.getIndustryListdata();
        } else {
            customerInquiryModel.getEnquiryType();
            customerInquiryModel.getSortType();
            customerInquiryModel.getReverseLookupTreeNodeByEn(companyNo);
        }
        getData();
    }

    private void getData() {
        isLoadMore = false;
        page = 1;
        customerInquiryModel.getDemandHallList(userid, sortid, enquiryid, tabName, searchName, companyNo, page);
    }

    /***
     * 显示列表数据
     * */
    public void getCustomerInquiryTabList(List<DictEntity3> data) {
        if (null != data && data.size() > 0) {
            binding.linChoicelass.setVisibility(View.VISIBLE);
            dictData = data;
            binding.tabLayout.removeAllTabs();
            for (int i = 0; i < data.size(); i++) {
                binding.tabLayout.addTab(binding.tabLayout.newTab().setText(data.get(i).getName()), i==0);
            }
            binding.tabLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.tabLayout.getTabAt(0).select();
                }
            }, 100);

        } else {
            binding.linChoicelass.setVisibility(View.GONE);
        }
    }

    /***
     *     返回状态数据
     */
    public void getEnquirtTypeList(List<EnquiryTypeEntity> enquiryTypelist) {
        enquirylist.clear();
        enquirylist.addAll(enquiryTypelist);
    }

    /***
     *     返回用户数据
     */
    public void getUserTypeList(List<EnquiryTypeEntity> userTypelist) {
        userlist.clear();
        userlist.addAll(userTypelist);
    }

    /****
     *     返回排序数据
     */
    public void getSortTypeList(List<EnquiryTypeEntity> sortTypelist) {
        sortlist.clear();
        sortlist.addAll(sortTypelist);
    }

    /****
     * 获取列表数据
     */
    public void setDemandHallList(List<DemandHallListEntity> demandHallListEntityList) {
        binding.demandList.refreshComplete();
        if (isLoadMore) {
            binding.demandList.loadMoreComplete();
            if (demandHallListEntityList.size() > 0) {
                demandHallAdapter.addDatas(demandHallListEntityList);
            } else {
                binding.demandList.setLoadingMoreEnabled(false);
            }
            binding.demandList.setVisibility(View.VISIBLE);
        } else {
            binding.demandList.refreshComplete();
            if (demandHallListEntityList.size() > 0) {
                binding.demandList.setVisibility(View.VISIBLE);
                binding.blankView.setVisibility(View.GONE);
                demandHallAdapter.setDatas(demandHallListEntityList);
                binding.demandList.setLoadingMoreEnabled(true);
            } else {
                binding.blankView.setVisibility(View.VISIBLE);
                demandHallAdapter.setDatas(null);
                binding.demandList.setVisibility(View.GONE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SHOPPING_LIST_LOGIN) {
            SharedPreferenceUtil.getInstance().saveString("EVENT_SHOPPING_TYPE", "");
            customerInquiryModel.showUrl(shoppingNo, context);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_EXPANDED) {
            if (layoutParams != null) {
                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                binding.llContainer.setLayoutParams(layoutParams);
                isParentAppBarCollapsed = false;
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_COLLAPSED) {
            if (layoutParams != null) {
                isParentAppBarCollapsed = true;
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_APPBAR_STATE_COMMON) {
            if (layoutParams != null) {
                layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL);
                binding.llContainer.setLayoutParams(layoutParams);
                isParentAppBarCollapsed = false;
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_BAOJIA_REFRESH) {
            getData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }


    public void showTabIndustryList(IndustryHomeListEntity data) {
        if (data.getIsEnabled() == 1 && data.getIndustryInfo().size() > 0  ) {
            binding.linHy.setVisibility(View.VISIBLE);
            list_Industry.clear();
//            list_Industry.add(new IndustryHomeListEntity.IndustryItem(0,"全部"));
            list_Industry.addAll(data.getIndustryInfo());
            binding.tabIndustry.removeAllTabs();
            for (int i = 0; i < list_Industry.size(); i++) {
                binding.tabIndustry.addTab(binding.tabIndustry.newTab().setText(list_Industry.get(i).getName()), choice_Industry == i);
            }
            binding.tabIndustry.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.tabIndustry.getTabAt(choice_Industry).select();
                }
            }, 100);
        } else {
            binding.linHy.setVisibility(View.GONE);
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}